package com.xxb.common.result;

import com.xxb.common.exception.SystemErrorEnum;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author RenGaoshuai
 * @date 2023/7/25 10:02
 * @description
 */
@Data
public class R<T> {

    private Integer code;

    private String message;

    private T data;

    private LocalDateTime time;

    private String traceId;

    public R() {

    }

    public R(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.time = LocalDateTime.now();
    }

    public R(Integer code, String message, T data, String traceId) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.time = LocalDateTime.now();
        this.traceId = traceId;
    }

    public boolean isSuccess() {
        return code == 200;
    }

    public boolean isFail() {
        return !isSuccess();
    }

    public static <T> R<T> ofSuccess() {
        return ofSuccess(null);
    }

    public static <T> R<T> ofFail() {
        return ofFail(SystemErrorEnum.SYSTEM_ERROR);
    }

    public static <T> R<T> ofFail(String message) {
        return ofFail(-1, message);
    }

    public static <T> R<T> ofFail(Integer code, String message) {
        return new R<>(code, message, null);
    }

    public static <T> R<T> ofFail(Integer code, String message, String traceId) {
        return new R<>(code, message, null, traceId);
    }

    public static <T> R<T> ofFail(SystemErrorEnum errorType) {
        return ofFail(errorType.getCode(), errorType.getMessage());
    }

    public static <T> R<T> ofFail(SystemErrorEnum errorType, String traceId) {
        return ofFail(errorType.getCode(), errorType.getMessage(), traceId);
    }

    public static <T> R<T> ofSuccess(T data) {
        return new R<>(200, "处理成功", data);
    }

    public static <T> R<T> ofMessage(int code, String message, T data) {
        return new R<>(code, message, data);
    }

    public static <T> R<T> ofMessage(int code, String message) {
        return ofMessage(code, message, null);
    }
}

